package com.desire.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

/**
 * @Description:
 * @Author: littleDesire
 * @Date: 2022-06-08 19:34
 * @Version: 1.0
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 自定义认证
        //String xToken = request.getHeader("x-token");
        //System.out.println(xToken);

        // 基本认证
        String authorization = request.getHeader("authorization");
        if (null != authorization && authorization.startsWith("Basic")) {
            //解码
            String[] tokens = authorization.split(" ");
            String token = tokens[1];
            String userName = new String(Base64.getDecoder().decode(token));
            if ("admin:123".equals(userName)) {
                return true;
            } else {
                response.setStatus(401);
                return false;
            }
        } else {
            response.setStatus(401);
            return false;
        }
       // return true;
    }
}
